//
//  SelectCell.m
//  diaoyuren
//
//  Created by 钓鱼人 on 16/2/17.
//  Copyright © 2016年 game. All rights reserved.

#import "SelectCell.h"
#import "UserHeadBnt.h"
#import "TYAttributedLabel.h"
#import "NSString+ChangeChange.h"
#import "UIButton+WebCache.h"
#import "NSString+ChangePPPPP.h"
#import "NSString+ClearPPPP.h"
#import "NSString+HtmlCharact.h"
#import "SDPhotoGroup.h"
#import "SDPhotoBrowser.h"
#import "MBButtonWithFontAdapter.h"
#import "MBLabelWithFontAdapter.h"
#import "MBTextFieldWithFontAdapter.h"
#import "MBTextViewWithFontAdapter.h"
#import "Masonry.h"
#import "UIImageView+WebCache.h"
@interface SelectCell ()<SDPhotoBrowserDelegate,TYAttributedLabelDelegate>
@property (nonatomic,strong) UserHeadBnt *hearBtn;
@property (nonatomic,strong) MBLabelWithFontAdapter *title;
@property (nonatomic,strong) MBLabelWithFontAdapter *time;
@property (nonatomic,strong) MBButtonWithFontAdapter *local;
@property (nonatomic,strong) AppDelegate *app;
@property (nonatomic,assign) BOOL webisLoad;
@property (nonatomic,strong) TYAttributedLabel *contentLab;
@property (nonatomic,strong) NSMutableArray *imageModelAry;
@property (nonatomic,strong) NSMutableArray *videoModelAry;
@property (nonatomic,strong) SDPhotoBrowser *browser;
@property (nonatomic,assign) BOOL isLoad;

@end

@implementation SelectCell

-(NSMutableArray *)imageModelAry{
    if (!_imageModelAry) {
        _imageModelAry  = [NSMutableArray array];
    }
    return _imageModelAry;
}

-(NSMutableArray *)videoModelAry{
    if (!_videoModelAry) {
        _videoModelAry = [NSMutableArray array];
    }
    return _videoModelAry;
}


-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
     
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        self.app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    
        [self CeratUserHeadBtn];
        [self CreatTitlss];
        
        _contentLab = [[TYAttributedLabel alloc]initWithFrame:CGRectMake(10, 0, SCREEN_WIDTH-20, 0)];
        
        [self.contentView addSubview:_contentLab];
        _contentLab.userInteractionEnabled = YES;
        [self setUiAlpha:0];
        _contentLab.delegate = self;
        
        self.backgroundColor = [UIColor whiteColor];
    }
    return self;
}

-(void)setUiAlpha:(CGFloat)alpha{
    _hearBtn.alpha = alpha;
    _title.alpha = alpha;
    _time.alpha = alpha;
    _local.alpha = alpha;

}

-(void)setModel:(SelectthreadModel *)model{
    _model = model;
    if (_model != nil) {
        [self setUiAlpha:1];
        
        _hearBtn.userName.text = _model.author;
        
        if (_model.position!=nil) {
            [_hearBtn.flood setTitle:[NSString stringWithFormat:@"  %@  ",@"只看楼主"] forState:UIControlStateNormal];
            _hearBtn.live.text = [NSString stringWithFormat:@"  Lv.%@  ",_model.level];
        }
        
        [self.hearBtn.userhead sd_setImageWithURL:[NSURL URLWithString:_model.avatar]];
        _title.text = _model.title;
        _time.text = _model.create_time;
        
        [_local setTitle:_model.location forState:UIControlStateNormal];
        if (_model.location.length==0) {
            _local.alpha = 0;
            
        }else{
            _local.alpha = 1;
        }
        
        if (self.isLoad) {
            return;
        }
        
        [self.imageModelAry addObjectsFromArray:_model.imgs];
        [self.videoModelAry addObjectsFromArray:_model.video];
   
        NSMutableArray * textArray = [NSMutableArray arrayWithArray:[_model.message componentsSeparatedByString:@"\n"]];
        NSInteger index = 0;
      
        for (NSString *text in textArray) {
            NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithString:text];

            if ([text rangeOfString:@"<!--DY-VIDEO"].length!=0) {
                
                for (SelectVideoModel *model in self.videoModelAry) {
                    
                    if ([text rangeOfString:model.video_mark].length!=0) {
                    UIWebView   *webview = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH-20, ((SCREEN_WIDTH-20)*200)/300)];
                    webview.scrollView.scrollEnabled = NO;
                    NSURL *url = [NSURL URLWithString:model.url];
    
                    NSURLRequest *request = [NSURLRequest requestWithURL:url];
                    [webview loadRequest:request];
                    [_contentLab appendView:webview];
                    [_contentLab appendText:@"\n"];
                  }
                    
                }
                
            }else
            if ([text rangeOfString:@"<!--DY-IMG-"].length!=0){
               
                
                for (SelectImageModel *model in self.imageModelAry) {
                    
                    if ([text  rangeOfString:model.img_mark].length!=0) {
                        
                         CGFloat bili = (SCREEN_WIDTH-20)/model.width;
                        UIImageView   *imageview = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH-20, model.height*bili)];
                        imageview.userInteractionEnabled = YES;
                        imageview.tag = [self.imageModelAry indexOfObject:model];
                        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(ImageTapClick:)];
                        [imageview addGestureRecognizer:tap];
                        [imageview sd_setImageWithURL:[NSURL URLWithString:model.url]];
                        [_contentLab appendView:imageview];
                         [_contentLab appendText:@"\n"];
                    }
                    
                }
            }

            else{
                
                if ([text rangeOfString:@"<strong>"].length!=0) {
                    
                    NSMutableAttributedString *strongString = [[NSMutableAttributedString alloc]initWithString:[text ClearStrong]];
                    [strongString addAttributeFont:[UIFont systemFontOfSize:SCREEN_WIDTH*0.06]];
                     [_contentLab appendTextAttributedString:strongString];
                    
                }else if ([text rangeOfString:@"http"].length!=0){
                    
                    NSRange range = [text rangeOfString:@"http"];
                    
                    [_contentLab appendText:[text substringToIndex:range.location]];
                    [_contentLab appendLinkWithText:[text substringFromIndex:range.location] linkFont:font(SCREEN_WIDTH*0.045) linkColor:mainColor underLineStyle:kCTUnderlineStyleNone linkData:[text substringFromIndex:range.location]];
                    
                }
                
            else{
                    [attributedString addAttributeFont:font(SCREEN_WIDTH*0.045)];
                    [_contentLab setCharacterSpacing:3];
                     [_contentLab appendTextAttributedString:attributedString];
                }
                 [_contentLab appendText:@"\n"];
            }
            index++;
        }
        
        [self.imageModelAry addObjectsFromArray:_model.attachments];

        for (SelectImageModel *model in _model.attachments) {
            
            CGFloat bili = (SCREEN_WIDTH-20)/model.width;
            UIImageView   *imageview = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH-20, model.height*bili)];
            
            imageview.tag = [self.imageModelAry indexOfObject:model];
            [imageview sd_setImageWithURL:[NSURL URLWithString:model.url]];
            imageview.userInteractionEnabled = YES;
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(ImageTapClick:)];
            [imageview addGestureRecognizer:tap];
            [_contentLab appendView:imageview];
            [_contentLab appendText:@"\n"];
        }

        [_contentLab sizeToFit];

      CGFloat hhh = [_contentLab getHeightWithWidth:SCREEN_WIDTH-20];
        _contentLab.height = hhh;
        
        self.cellHeight = hhh+160;
        self.height = self.cellHeight;
        self.isLoad = YES;
        
    }
}

-(void)attributedLabel:(TYAttributedLabel *)attributedLabel textStorageClicked:(id<TYTextStorageProtocol>)textStorage atPoint:(CGPoint)point{

    if ([textStorage isKindOfClass:[TYLinkTextStorage class]]) {
        NSString *linkStr = ((TYLinkTextStorage*)textStorage).linkData;
        
        if ([linkStr rangeOfString:@"http"].length!=0) {
            
            NSURL *url = [NSURL URLWithString:linkStr];
            
            if ([linkStr rangeOfString:@"taobao"].length!=0) {
                
                NSString *sss = [linkStr substringFromIndex:[linkStr rangeOfString:@"://"].location];
                NSString *taobaoUrl = [NSString stringWithFormat:@"taobao%@",sss];
                
                NSURL *uuuu = [NSURL URLWithString:taobaoUrl];
                
                if ([[UIApplication sharedApplication] canOpenURL:uuuu]) {
                    // 如果已经安装淘宝客户端，就使用客户端打开链接
                    [[UIApplication sharedApplication] openURL:uuuu];
                } else {
                  
                    [[UIApplication sharedApplication] openURL:url];
                }
            }else if ([linkStr rangeOfString:@"http://www.diaoyur.net/thread"].length!=0){
                
                NSError *error = NULL;
                NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"([0-9]{1,})" options:NSRegularExpressionCaseInsensitive error:&error];
                NSTextCheckingResult *result = [regex firstMatchInString:linkStr options:0 range:NSMakeRange(0, [linkStr length])];
                if (result) {
                    
                    NSString *tid = [linkStr substringWithRange:result.range];
                    NSString *turl  = [NSString stringWithFormat:@"http://api.diaoyur.cn/app/index.php?version=4&module=viewthread&tid=%@",tid];
                    
                    if ([self.deleget respondsToSelector:@selector(NewAticleOfLinkWhithTid:AndTurl:)]) {
                        [self.deleget NewAticleOfLinkWhithTid:tid AndTurl:turl];
                    }
                }

            
            }
            
            else{
                [ [ UIApplication sharedApplication] openURL:[ NSURL URLWithString:linkStr]];
            
            }
        }
    }

}

-(void)ImageTapClick:(UITapGestureRecognizer *)tap{
   
    _browser = [[SDPhotoBrowser alloc] init];
    _browser.sourceImagesContainerView = self.contentLab; // 原图的父控件
    _browser.imageCount = self.imageModelAry.count; // 图片总数
    _browser.delegate = self;
    
    _browser.alpha = 0;
    _browser.currentImageIndex = (int)tap.view.tag;
    [_browser show];
    
    [UIView animateWithDuration:0.8 animations:^{
        _browser.alpha = 1;
    }];
}
#pragma mark - photobrowser代理方法
// 返回临时占位图片（即原来的小图）
- (UIImage *)photoBrowser:(SDPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index
{
    return nil;//[self.subviews[ininin] currentImage];
}

// 返回高质量图片的url
- (NSURL *)photoBrowser:(SDPhotoBrowser *)browser highQualityImageURLForIndex:(NSInteger)index
{
    
    SelectImageModel *model = self.imageModelAry[index];
    NSString *urlStr = [model.url stringByReplacingOccurrencesOfString:@"thumbnail" withString:@"bmiddle"];
    return [NSURL URLWithString:urlStr];
}



-(void)drawRect:(CGRect)rect{
    [super drawRect:rect];

    _contentLab.y = Height(_local)+10;

}

/**
 *  详情顶部 头像、名称视图
 */
-(void)CeratUserHeadBtn{
    [_hearBtn removeFromSuperview];
    _hearBtn = [[UserHeadBnt alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 60)];
    [_hearBtn addTarget:self action:@selector(ShowSpace) forControlEvents:UIControlEventTouchUpInside];
    [_hearBtn.flood addTarget:self action:@selector(ShowFlood:) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:_hearBtn];
}
/**
 *  点击显示用户名,头像部分的 hearBtn 查看个人空间
 */
-(void)ShowSpace{
    [self.deleget ShowSpaceCLick:_model.authorid];
}

/**
 *  点击只看楼主
 */
-(void)ShowFlood:(UIButton*)btn{

    btn.selected = !btn.selected;
    
    if (btn.selected) {
        btn.backgroundColor = mainColor;
        
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    }else{
        btn.backgroundColor = [UIColor whiteColor];
        
        [btn setTitleColor:mainColor forState:UIControlStateNormal];
        
    }
    [self.deleget ShowFlood:_model.tid AndAuthorId:_model.authorid];
}

/**
 *  标题、时间、地址
 */
-(void)CreatTitlss{

    _title = [self CrecLabel:_title WhithFont:0.06 AndColor:[UIColor blackColor] AndAlpha:0.9];
    _title.font = font(18);
   
    [_title mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_hearBtn.mas_bottom).offset(5);
        make.left.equalTo(@10);
        make.right.equalTo(@-10);
    }];
    
    
  
    _time = [self CrecLabel:_time WhithFont:0.035 AndColor:textcolor AndAlpha:0.4];
    
    [_time mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_title.mas_bottom).offset(5);
        make.left.equalTo(_title.mas_left);
    }];

    
    _local = [self CreatBntWhithType:UIButtonTypeCustom AndBntImgName:@"dingwei" WhithFont:0.035];
    
    _local.imageEdgeInsets = UIEdgeInsetsMake(3, 0, 3, 0);
    [_local setTitleColor:textcolor forState:UIControlStateNormal];
    
    [_local mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_time.mas_right).offset(15);
        make.centerY.equalTo(_time.mas_centerY);
    }];
}


-(MBButtonWithFontAdapter *)CreatBntWhithType:(UIButtonType)type AndBntImgName:(NSString *)string WhithFont:(CGFloat )font
{
    MBButtonWithFontAdapter *bnt=[MBButtonWithFontAdapter buttonWithType:type];
    
    [bnt setImage:[UIImage imageNamed:string] forState:UIControlStateNormal];
    bnt.titleLabel.font = font(12);

    [self.contentView addSubview:bnt];
    return bnt;
}

-(MBLabelWithFontAdapter *)CrecLabel:(MBLabelWithFontAdapter *)label WhithFont:(CGFloat )font AndColor:(UIColor *)color AndAlpha:(CGFloat)alpha{
    
    label = [[MBLabelWithFontAdapter alloc]init];
    label.font = font(12); ;//[UIFont fontWithName:@"hanyiqihei-50s" size:font];//
    label.textColor = color;
    label.alpha = alpha;
    label.numberOfLines = 0;
    [self.contentView addSubview:label];
    return label;
}
@end